<?php

defined('IN_IA') or exit('Access Denied');

// 单图上传
function tpl_form_field_image2($name,$value){
    $thumb = empty($value) ? 'images/global/nopic.jpg' : $value;
    $thumb = tomedia($thumb);

    $html = <<<EOF
        <div class="input-group ">
            <input type="text" name="$name" value="$value" class="form-control" autocomplete="off">
            <span class="input-group-btn">
                <button class="btn btn-default" type="button" onclick="showImageDialog(this);" data-original-title="" title="">选择图片</button>
            </span>
        </div>
        <div class="input-group " style="margin-top:.5em;">
            <img src="$thumb" class="img-responsive img-thumbnail" width="150" title="图片未找到.">
            <em class="close" style="position:absolute; top: 0px; right: -14px;" title="删除这张图片" onclick="deleteImage(this)">×</em>
        </div>
EOF;

    return $html;
}

// 多图上传
function tpl_form_field_multi_image2($name, $value = array(), $options = array()) {
    global $_W;
    $options['multiple'] = true;
    $options['direct'] = false;
    $options['fileSizeLimit'] = intval($GLOBALS['_W']['setting']['upload']['image']['limit']) * 1024;
    if (isset($options['dest_dir']) && !empty($options['dest_dir'])) {
        if (!preg_match('/^\w+([\/]\w+)?$/i', $options['dest_dir'])) {
            exit('图片上传目录错误,只能指定最多两级目录,如: "we7_store","we7_store/d1"');
        }
    }
    $s = '';
    if (!defined('TPL_INIT_MULTI_IMAGE')) {
        $s = '
<script type="text/javascript">
    function uploadMultiImage(elm) {
        var name = $(elm).next().val();
        util.image( "", function(urls){
            $.each(urls, function(idx, url){
                $(elm).parent().parent().next().append(\'<div class="multi-item"><img onerror="this.src=\\\'./resource/images/nopic.jpg\\\'; this.title=\\\'图片未找到.\\\'" src="\'+url.url+\'" class="img-responsive img-thumbnail"><input type="hidden" name="\'+name+\'[]" value="\'+url.attachment+\'"><em class="close" title="删除这张图片" onclick="deleteMultiImage(this)">×</em></div>\');
            });
        }, ' . json_encode($options) . ');
    }
    function deleteMultiImage(elm){
        $(elm).parent().remove();
    }
</script>';
        define('TPL_INIT_MULTI_IMAGE', true);
    }

    $s .= <<<EOF
<div class="input-group">
    <input type="text" class="form-control" readonly="readonly" value="" placeholder="批量上传图片" autocomplete="off">
    <span class="input-group-btn">
        <button class="btn btn-default" type="button" onclick="uploadMultiImage(this);">选择图片</button>
        <input type="hidden" value="{$name}" />
    </span>
</div>
<div class="input-group multi-img-details">
EOF;
    if (is_array($value) && count($value) > 0) {
        foreach ($value as $row) {
            $s .= '
<div class="multi-item">
    <img src="' . tomedia($row) . '" onerror="this.src=\'./resource/images/nopic.jpg\'; this.title=\'图片未找到.\'" class="img-responsive img-thumbnail">
    <input type="hidden" name="' . $name . '[]" value="' . $row . '" >
    <em class="close" title="删除这张图片" onclick="deleteMultiImage(this)">×</em>
</div>';
        }
    }
    $s .= '</div>';

    return $s;
}

if (!(function_exists("addCeshi")))
{
    function addCeshi($params){
        $ceshi_exit = pdo_tableexists("ceshi");

        if(!$ceshi_exit){
            $sql = "
                CREATE TABLE `ims_ceshi` (
                  `id` int(11) NOT NULL AUTO_INCREMENT,
                  `content` text,
                  `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
                  PRIMARY KEY (`id`)
                ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
            ";
            pdo_query($sql);
        }

        $content = $params;
        if(is_array($params)){
            $content = json_encode($params);
        }
        pdo_insert("ceshi",array('content'=>$content));
    }
}

/**
 * 模拟get请求
 * @param string $url
 */
function chttp_get($url) {
    load()->func('communication');
    return ihttp_get($url);
}

/**
 * 模拟post请求
 * @param string $url
 * @param array $data
 */
function chttp_post($url, $data) {
    load()->func('communication');
    return ihttp_post($url, $data);
}

/**
 * request 高级请求
 * @param string $url 请求地址
 * @param array $post 要POST请求的数据，为空时则会以GET形式请求
 * @param array $extra 请求附加值
 * @param int $timeout 超时时间
 * @return Ambigous <multitype:unknown string , multitype:unknown string Ambigous <> Ambigous <boolean, string> >
 */
function chttp_request($url, $post, $extra, $timeout) {
    load()->func('communication');
    return ihttp_request($url, $post, $extra, $timeout);
}

/**
 * 获取会员级别
 * @param unknown $credit1
 * @return Ambigous <Ambigous <>>
 */
function getLevel($credit4){
    if(!empty($_SESSION['groups'])){
        $group_old = unserialize($_SESSION['groups']);
        
        $group_new = array();
        $array = array();
        foreach ($group_old as $key => $item){
            $group  = explode(",", $item);
            $group_new[$group[0]] = $group[1];
            $array[] = $group[0];
        }
        
        $index = getMinValue($credit4,$array);
        
        return $group_new[$index];
    }else{
        return "普通";
    }
    
}

/**
 * 获取相邻两位数的最小值
 * @param unknown $goodsprice
 * @param unknown $array
 * @return unknown
 */
function getMinValue($value, $array){
    $index = 0;
    $c = false;
    foreach ($array as $key=>$item){
        $dif = $value - $item;
        if($dif > 0){
            if (!$c){
                $c = $dif;
                continue;
            }else if ($dif < $c){
                $c = $dif;
                $index = $key;
            }
        }
    }
    return $array[$index];
}

/**
 * 预留方法   做图片分库处理时用到
 * @param unknown $url
 * @return unknown
 */
function save_media($url){
    return $url;
}

/**
 * 补全图片路径
 * @param unknown $list
 * @param string $fields
 * @return unknown|string
 */
function set_medias($list = array(), $fields = null){
    if (empty($fields)) {
        foreach ($list as &$row) {
            $row = tomedia($row);
        }
        return $list;
    }
    if (!is_array($fields)) {
        $fields = explode(',', $fields);
    }
    if (is_array2($list)) {
        foreach ($list as $key => &$value) {
            foreach ($fields as $field) {
                if (isset($list[$field])) {
                    $list[$field] = tomedia($list[$field]);
                }
                if (is_array($value) && isset($value[$field])) {
                    $value[$field] = tomedia($value[$field]);
                }
            }
        }
        return $list;
    } else {
        foreach ($fields as $field) {
            if (isset($list[$field])) {
                $list[$field] = tomedia($list[$field]);
            }
        }
        return $list;
    }
}

function html_images($detail = '')
{
    $detail = htmlspecialchars_decode($detail);
    preg_match_all("/<img.*?src=[\'| \"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg]?))[\'|\"].*?[\/]?>/", $detail, $imgs);
    $images = array();
    if (isset($imgs[1])) {
        foreach ($imgs[1] as $img) {
            $im       = array(
                "old" => $img,
                "new" => save_media($img)
            );
            $images[] = $im;
        }
    }
    foreach ($images as $img) {
        $detail = str_replace($img['old'], $img['new'], $detail);
    }
    return $detail;
}

/**
 * 是否多维数组
 * @param unknown $array
 * @return boolean
 */
function is_array2($array){
    if (is_array($array)) {
        foreach ($array as $k => $v) {
            return is_array($v);
        }
        return false;
    }
    return false;
}

/**
 * 返回相应时间戳
 * @param number $y 年
 * @param number $m 月
 * @param number $d 日
 * @return number
 */
function getDay($d=0,$m=0,$y=0){
    $day['start'] = mktime(0,0,0,date("m")+$m,date("d")+$d,date("Y")+$y);
    $day['end']   = mktime(23,59,59,date("m")+$m,date("d")+$d,date("Y")+$y);
    return $day;
}

/**
 * 获取最后一天
 * @param unknown $year
 * @param unknown $month
 * @return string
 */
function get_last_day($year, $month){
    return date('t', strtotime("{$year}-{$month} -1"));
}

/**
 * 获取年月周日的开始时间与结束时间
 * @param unknown $type
 * @return multitype:number
 */
function arrangeTime($type){
    switch ($type) {
        case 'month':
            $y   = date("Y",time());
            $m   = date("m",time());
            $d   = date("d",time());
            $t0  = date('t');                   // 本月一共有几天
            $d0  = mktime(0,0,0,$m,1,$y);       // 创建本月开始时间
            $d1  = mktime(23,59,59,$m,$t0,$y);  // 创建本月结束时间
            break;
        case 'week':
            $w   = date( "w",time());   //这天是星期几
            $d0  = mktime   (0,0,0,date( "m"), date( "d") - $w,date( "Y"));       //创建周开始时间
            $d1  = mktime   (23,59,59,date( "m"), date( "d") - $w + 6,date( "Y"));//创建周结束时间
            break;
        case 'day':
            $d0  = mktime (0,0,0, date( "m"), date( "d"), date( "Y"));   //创建日开始时间
            $d1  = mktime (23,59,59, date( "m"), date( "d"), date( "Y"));//创建日结束时间
            break;
        case 'year':
            $d0 = strtotime(date("Y",time())."-1"."-1"); //本年开始
            $d1 = strtotime(date("Y",time())."-12"."-31"); //本年结束
            break;
    }
    return array($d0, $d1);
}

/**
 * 返回间隔天数
 * @param unknown $startDay
 * @param unknown $endDay
 * @return number
 */
function getDaySum($startDay,$endDay){
    $startDay = date("Y-m-d",$startDay);
    $endDay = date("Y-m-d",$endDay);
    $datetime1 = date_create($startDay);
    $datetime2 = date_create($endDay);
    $interval = date_diff($datetime1, $datetime2);
    return intval($interval->format('%R%a'));
}

/**
 * json返回数据
 * @param number $status
 * @param string $return
 */
if(!function_exists('show_json')){
    function show_json($status = 1, $return = null){
        $ret = array(
            'status' => $status
        );
        if ($return) {
            $ret['result'] = $return;
        }
        die(json_encode($ret));
    }
}

/**
 * 判断是否微信端登录
 * @return boolean
 */
function is_weixin(){
    if (empty($_SERVER['HTTP_USER_AGENT']) || strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') === false && strpos($_SERVER['HTTP_USER_AGENT'], 'Windows Phone') === false) {
        die("<!DOCTYPE html>
            <html>
                <head>
                    <meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'>
                    <title>抱歉，出错了</title><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'><link rel='stylesheet' type='text/css' href='https://res.wx.qq.com/connect/zh_CN/htmledition/style/wap_err1a9853.css'>
                </head>
                <body>
                    <div class='page_msg'><div class='inner'><span class='msg_icon_wrp'><i class='icon80_smile'></i></span><div class='msg_content'><h4>请在微信客户端打开链接</h4></div></div></div>
                </body>
            </html>");
        return false;
    }
    return true;
}

/**
 * 生成不重复随机数
 * @param unknown $table
 * @param unknown $field
 * @param unknown $prefix
 * @return string
 */
function createRandom($table, $field, $number){
    if(empty($number)){
        $number = 4;
    }
    
    $billno = random($number);
    while (1) {
        $count = pdo_fetchcolumn('select count(*) from ' . tablename($table) . " where {$field}=:billno limit 1", array(':billno' => $billno));
        if ($count <= 0) {
            break;
        }
        createRandom($table, $field, $number);
    }
    return $billno;
}

/**
 * 生成订单
 * @param unknown $table
 * @param unknown $field
 * @param unknown $prefix
 * @return string
 */
function createNO($table, $field, $prefix){
    $billno = date('YmdHis') . random(4, true);
    while (1) {
        $count = pdo_fetchcolumn('select count(*) from ' . tablename($table) . " where {$field}=:billno limit 1", array(':billno' => $billno));
        if ($count <= 0) {
            break;
        }
        $billno = date('YmdHis') . random(4, true);
    }
    return $prefix . $billno;
}

/**
 * 导出Excel表格
 * @param unknown $data
 * @param string $file_name
 */
function outputXlsHeader($columns,$exportlist,$filename="数据统计"){
    header("Content-type:text/html;charset=UTF-8;" );
    header('Content-Type: text/xls;');
    header("Content-type:application/vnd.ms-excel;charset=UTF-8;" );
    header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
    header('Expires:0');
    header('Pragma:public');
    $table_data = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">';
    $table_data .= '<head>';
    $table_data .= '<meta http-equiv="expires" content="Mon, 06 Jan 1999 00:00:01 GMT">';
    $table_data .= '<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name></x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->';
    $table_data .= '</head>';
    $table_data .= '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
    $table_data .= '<table border="1">';
    $table_data .= '<tr>';
    foreach ($columns as $column){
        $height = empty($column['height']) ? 30 : $column['height'];
        $width = empty($column['width']) ? 100 : $column['width'];
        $table_data .="<td height='".$height."' width='".$width."'>".$column['title']."</td>";
    }
    $table_data .= '</tr>';
    $table_data .= '<tr>';
    foreach ($exportlist as $line){
        $len = count($columns);
        for ($i = 0; $i < $len; $i++) {
            $value = isset($line[$columns[$i]['field']]) ? $line[$columns[$i]['field']] : '';
            $table_data .= '<td>' . $value . '</td>';
        }
        $table_data .= '</tr>';
    }
    $table_data .='</table>';
    echo $table_data;
    die();
}

/**
 * 浏览器友好的变量输出
 * @param mixed $var 变量
 * @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
 * @param string $label 标签 默认为空
 * @param boolean $strict 是否严谨 默认为true
 * @return void|string
 */
if(!function_exists('dump')){
    function dump($var, $echo=true, $label=null, $strict=true) {
        $label = ($label === null) ? '' : rtrim($label) . ' ';
        if (!$strict) {
            if (ini_get('html_errors')) {
                $output = print_r($var, true);
                $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
            } else {
                $output = $label . print_r($var, true);
            }
        } else {
            ob_start();
            var_dump($var);
            $output = ob_get_clean();
            if (!extension_loaded('xdebug')) {
                $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
                $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
            }
        }
        if ($echo) {
            echo($output);
            return null;
        }else
            return $output;
    }
}

/**
 * 获取积分商城用户信息（同步系统积分和余额）
 * @param string $openid
 * @return boolean
 */
function getMember($openid = ''){
    global $_W;
    load()->model('mc');
    
    $uid = intval($openid);
    if (empty($uid)) {
        $uid   = mc_openid2uid($openid);
        $info = pdo_fetch('select * from ' . tablename('mc_members') . ' where uid=:uid and uniacid=:uniacid limit 1', array(
            ':uniacid' => $_W['uniacid'],
            ':uid' => $uid
        ));
    } else {
        $info = pdo_fetch('select * from ' . tablename('mc_members') . ' where uid=:uid and uniacid=:uniacid limit 1', array(
            ':uniacid' => $_W['uniacid'],
            ':uid' => $uid
        ));
    }
    return $info;
}

/**
 * 获取积分或余额
 * @param string $openid
 * @param unknown $credittypes
 * @return boolean
 */
function getCredits($openid = '', $credittypes = array('credit1', 'credit2','credit3','credit4')){
    global $_W;
    load()->model('mc');
    $uid   = mc_openid2uid($openid);
    $types = implode(',', $credittypes);
    if (!empty($uid)) {
        return pdo_fetch("SELECT {$types} FROM " . tablename('mc_members') . " WHERE `uid` = :uid limit 1", array(
            ':uid' => $uid
        ));
    }
}

/**
 * 获取当前用户的积分
 * @param string $openid
 * @param string $credittype
 * @return boolean
 */
function getCredit($openid = '', $credittype = 'credit1'){
    global $_W;
    load()->model('mc');
    $uid = mc_openid2uid($openid);
    if (!empty($uid)) {
        return pdo_fetchcolumn("SELECT {$credittype} FROM " . tablename('mc_members') . " WHERE `uid` = :uid", array(
            ':uid' => $uid
        ));
    }
}

/**
 * 设置积分
 * @param string $openid
 * @param string $credittype
 * @param number $credits
 * @param unknown $log
 */
function setCredit($openid = '', $credittype = 'credit1', $credits = 0, $log = array()){
    global $_W;
    
    $uid = intval($openid);
    if (empty($uid)) {
        load()->model('mc');
        $uid = mc_openid2uid($openid);
    }
    if (!empty($uid) && !empty($credits)) {
        $value     = pdo_fetchcolumn("SELECT {$credittype} FROM " . tablename('mc_members') . " WHERE `uid` = :uid", array(
            ':uid' => $uid
        ));
        $newcredit = $credits + $value;
        if ($newcredit <= 0) {
            $newcredit = 0;
        }
        pdo_update('mc_members', array(
            $credittype => $newcredit
        ), array(
            'uid' => $uid
        ));
        if (empty($log) || !is_array($log)) {
            $log = array(
                $uid,
                '未记录'
            );
        }
        $data = array(
            'uid' => $uid,
            'credittype' => $credittype,
            'uniacid' => $_W['uniacid'],
            'num' => $credits,
            'createtime' => TIMESTAMP,
            'operator' => intval($log[0]),
            'remark' => $log[1],
            'module' => MODULE_NAME,
        );
        pdo_insert('mc_credits_record', $data);
    }
}

/**
 * 是否关注
 * @param string $openid
 * @return boolean
 */
function followed($openid = ''){
    global $_W;
    $followed = !empty($openid);
    if ($followed) {
        $mf       = pdo_fetch("select follow from " . tablename('mc_mapping_fans') . " where openid=:openid and uniacid=:uniacid limit 1", array(
            ":openid" => $openid,
            ':uniacid' => $_W['uniacid']
        ));
        $followed = $mf['follow'];
    }
    return intval($followed);
}

/**
 * 验证会员登录
 */
function checkMember($openid){
    global $_W, $_GPC;
    load()->model('mc');
    
    if (strexists($_SERVER['REQUEST_URI'], '/web/')) {
        return;
    }
    if (empty($openid)) {
        $userinfo = mc_oauth_userinfo();
        $openid = $userinfo['openid'];
    }
    if (empty($openid)) {
        return;
    }
    
    $member   = getMember($openid);
    
    $level = pdo_fetchcolumn("select level from".tablename("account_wechats")." where uniacid = '".intval($_W['uniacid'])."' ");
    if (intval($level) == 4) {
        $userinfo = mc_oauth_userinfo();
    }
    
    $userinfo = empty($userinfo)?array():$userinfo;
    
    $followed = followed($openid);
    $uid      = 0;
    $mc       = array();
    
    if ($followed) {
        $uid = mc_openid2uid($openid);
        $mc  = mc_fetch($uid, array(
            'realname',
            'mobile',
            'avatar',
            'resideprovince',
            'residecity',
            'residedist',          
        ));
    }

    if (empty($member)) {
        $member = array(
            'uniacid' => $_W['uniacid'],
            'nickname' => !empty($mc['nickname']) ? strval($mc['nickname']) : strval($userinfo['nickname']),
            'avatar' => !empty($mc['avatar']) ? $mc['avatar'] : $userinfo['avatar'],
            'gender' => !empty($mc['gender']) ? $mc['gender'] : $userinfo['sex'],
            'resideprovince' => !empty($mc['residecity']) ? $mc['resideprovince'] : $userinfo['province'],
            'residecity' => !empty($mc['residecity']) ? $mc['residecity'] : $userinfo['city'],
            'residedist' => !empty($mc['residecity']) ? $mc['residecity'] : $userinfo['area'],
            'createtime' => time(),
            'credit1' => 0,
        );
        pdo_insert('mc_members', $member);
        $member['uid'] = pdo_insertid();
        $uid = $member['uid'];
    }

    $fans = pdo_fetch("SELECT * FROM ".tablename("mc_mapping_fans")." WHERE openid = '".$openid."' ");
    if(empty($fans)){
        pdo_insert("mc_mapping_fans",array('openid'=>$openid,'uid'=>$member['uid'],'acid'=>$_W['acid'],'uniacid'=>$_W['uniacid'],'nickname'=>$member['nickname'],'followtime'=>time()));
    }else{
        pdo_update("mc_mapping_fans",array('uid'=>$member['uid']),array('openid'=>$openid));
        $fans = pdo_fetch("select nickname,tag from ".tablename("mc_mapping_fans")." where uniacid =:uniacid and openid=:openid ",array(':uniacid'=>$_W['uniacid'],':openid'=>$openid));
        if(!empty($fans['tag']) && empty($member['nickname'])){
            $tag = unserialize(base64_decode($fans['tag']));
            $member = array(
                'uid' => $member['uid'],
                'nickname' => $tag['nickname'],
                'avatar' => $tag['headimgurl'],
                'gender' => $tag['sex'],
                'resideprovince' => $tag['province'],
                'residecity' => $tag['city'],
            );
            pdo_update("mc_members",$member,array('uid'=>$member['uid']));
        }
        if(!empty($fans['nickname']) && empty($member['nickname'])){
            pdo_update("mc_members",array('nickname'=>$fans['nickname']),array('uid'=>$member['uid']));
        }
    }
    
    check_poster_member( array( 'uid' => $uid , 'openid' => $openid , 'nickname' => $member['nickname'] ) );

    $member['openid'] = $openid;
    return $member;
}


// 自动注册海报会员信息
function check_poster_member( $params = array() ){
    global $_W;
    if( empty($params['openid']) ){
        return false;
    }

    $member = pdo_fetch( "select id,uid,openid from ".tablename(MODULE_PREFIX."member") . " where openid = :openid ",array(':openid' => $params['openid']) );

    if( empty($member) ){
        $in_data = array(
            'uniacid'   => $_W['uniacid'],
            'uid'       => $params['uid'],
            'openid'    => $params['openid'],
            'nickname'  => $params['nickname'],
            'createtime' => time(),
        );
        pdo_insert(MODULE_PREFIX."member",$in_data);
    }

    return $member;
}

/**
 * 计算某个经纬度的周围某段距离的正方形的四个点
 *
 * @param lng float 经度
 * @param lat float 纬度
 * @param distance float 该点所在圆的半径，该圆与此正方形内切，默认值为0.5千米
 * @return array 正方形的四个点的经纬度坐标
 */
function squarePoint($lng, $lat, $distance = 0.5) {
    $earth_radius = 6371;//地球半径
    $dlng = 2 * asin(sin($distance / (2 * $earth_radius)) / cos(deg2rad($lat)));
    $dlng = rad2deg($dlng);

    $dlat = $distance / $earth_radius;
    $dlat = rad2deg($dlat);

    return array(
        'left-top' => array('lat' => $lat + $dlat, 'lng' => $lng - $dlng),
        'right-top' => array('lat' => $lat + $dlat, 'lng' => $lng + $dlng),
        'left-bottom' => array('lat' => $lat - $dlat, 'lng' => $lng - $dlng),
        'right-bottom' => array('lat' => $lat - $dlat, 'lng' => $lng + $dlng)
    );
}

/**
 * 获取距离
 * @param unknown $lat1
 * @param unknown $lng1
 * @param unknown $lat2
 * @param unknown $lng2
 * @param number $len_type
 * @param number $decimal
 * @return number
 */
function getDistance($lat1, $lng1, $lat2, $lng2, $len_type = 1, $decimal = 2) {
    $earth_radius = 6371;//地球半径
    $radLat1 = $lat1 * M_PI / 180;
    $radLat2 = $lat2 * M_PI / 180;
    $a = $lat1 * M_PI / 180 - $lat2 * M_PI / 180;
    $b = $lng1 * M_PI / 180 - $lng2 * M_PI / 180;

    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $s = $s * $earth_radius;
    $s = round($s * 1000);
    if ($len_type > 1) {
        $s /= 1000;
    }
    return round($s, $decimal);
}

/**
 * 发送海报随机触发消息
 */
function sendRandomNotice($poster_member_qr){
    global $_W;
	$config = getConfig();
    $poster = pdo_fetch("select * from ".tablename(MODULE_PREFIX.'poster')." where id = ".intval($poster_member_qr['posterid']));
    
    if(!empty($poster)){
        // 记录总的邀请次数
        pdo_update(MODULE_PREFIX."member","randomnum = randomnum + 1 ",array('uniacid'=>intval($_W['uniacid']),'uid'=>$poster_member_qr['uid']));
        
        // 记录单个海报邀请次数
        pdo_update(MODULE_PREFIX."qr","finish_random_nums = finish_random_nums + 1 ",array('id'=>intval($poster_member_qr['id'])));
        
        $desc = " 邀请任务完成 ";

        // 链接地址推送奖励
        if(intval($poster['sendtype']) == 0){
            if(!empty($poster['sendurl']) && !empty($poster['sendval'])){
                $desc .= " 推送一个链接地址 ".$poster['sendval'];
                if(!empty($poster['templateid'])){
                    $re_msg = $poster['sendval'];
                }else{
                    $re_msg = "<a href='" . $poster['sendurl'] . "'>" . $poster['sendval'] . "</a>";
                }
                
            }elseif(!empty($poster['sendval']) && empty($poster['sendurl'])){
                $re_msg = $poster['sendval'];
            }else{
                $re_msg = "已有“".$poster['random']."”位好友扫码了";
            }
            
            if(!empty($poster['templateid'])){
                sendTplNotice($poster_member_qr['openid'], $poster['templateid'], postdata('','',$re_msg),$poster['sendurl']);
            }else{
                sendCustomNotice($poster_member_qr['openid'], $re_msg);
            }
        }
        
        
        
    }
}

/**
 * 发送客服消息
 * @param unknown $openid
 * @param unknown $msg
 * @param string $url
 * @param string $account
 */
function sendCustomNotice($openid, $msg, $url = '', $account = null){ {
    if (!$account) {
        $account = getAccount();
    }
    if (!$account) {
        return;
    }
    $content = "";
    if (is_array($msg)) {
        foreach ($msg as $key => $value) {
            if (!empty($value['title'])) {
                $content .= $value['title'] . ":" . $value['value'] . "\n";
            } else {
                $content .= $value['value'] . "\n";
                if ($key == 0) {
                    $content .= "\n";
                }
            }
        }
    } else {
        $content = $msg;
    }

    // 双引号转单引号 得以让公众号识别
    $content = str_replace('"', "'", $content);

    if (!empty($url)) {
        $content .= "\n<a href='{$url}'>点击查看详情</a>";
    }

    return $account->sendCustomNotice(array(
        "touser" => $openid,
        "msgtype" => "text",
        "text" => array(
            'content' => urlencode($content)
        )
    ));
}}

/**
 * 发送模版消息
 * @param unknown $touser
 * @param unknown $template_id
 * @param unknown $postdata
 * @param string $url
 * @param string $account
 * @return void|Ambigous <boolean, multitype:unknown string , number, unknown, mixed, string>
 */
function sendTplNotice($touser, $template_id, $postdata, $url = '', $account = null){
    if (!$account) {
        $account = getAccount();
    }

    if (!$account) {
        return;
    }
    return $account->sendTplNotice($touser, $template_id, $postdata, $url);
}

/**
 * 引用微信基础接口类库
 * @return Ambigous <NULL, WeiXinAccount, YiXinAccount, WeiXinPlatform>|boolean
 */
function getAccount(){
    global $_W;
    load()->model('account');
    if (!empty($_W['acid'])) {
        return WeAccount::create($_W['acid']);
    } else {
        $acid = pdo_fetchcolumn("SELECT acid FROM " . tablename('account_wechats') . " WHERE `uniacid`=:uniacid LIMIT 1", array(
            ':uniacid' => $_W['uniacid']
        ));
        return WeAccount::create($acid);
    }
    return false;
}


/**
 * 返回图片
 * @param unknown $openid
 * @param unknown $mediaid
 * @return Ambigous <unknown, multitype:unknown string , number, mixed, string>
 */
function sendImage($openid, $mediaid){
    $account = getAccount();
    return $account->sendCustomNotice(array(
        "touser" => $openid,
        "msgtype" => "image",
        "image" => array(
            'media_id' => $mediaid
        )
    ));
}

/**
 * 返回音频
 * @param unknown $openid
 * @param unknown $mediaid
 * @return Ambigous <unknown, multitype:unknown string , number, mixed, string>
 */
function sendVoice($openid, $mediaid){
    $account = getAccount();
    return $account->sendCustomNotice(array(
        "touser" => $openid,
        "msgtype" => "voice",
        "voice" => array(
            'media_id' => $mediaid
        )
    ));
}

/**
 * 获取关注二维码
 * @param unknown $poster
 * @param unknown $member
 * @param number $goodsid
 * @return Ambigous <boolean, multitype:NULL unknown >|multitype:number NULL unknown string Ambigous <NULL, unknown> Ambigous <number, unknown, string, NULL>
 */
function getQR($poster, $openid){
    global $_W, $_GPC;
	$newtime = time()-2592000;
    $qr         = pdo_fetch("select * from " . tablename(MODULE_PREFIX."qr") . " where openid = '".$openid."' and posterid = ".intval($poster['id'])." and uniacid = ".intval($_W['uniacid'])." AND createtime > ".$newtime." order by id desc limit 1");
    
    if (empty($qr)) {
		pdo_delete(MODULE_PREFIX."qr", array('openid' => $openid,'posterid' => $poster['id'],'uniacid' => $_W['uniacid']));
        $uid = pdo_fetchcolumn("select uid from".tablename("mc_mapping_fans")." where openid = '".$openid."' ");

        $result = array();
        
        $level = pdo_fetchcolumn("select level from".tablename("account_wechats")." where uniacid = '".intval($_W['uniacid'])."' ");

        if (intval($level) == 4) {
            $uniaccount = getAccount();
            $result = getFixedTicket($poster, $openid, $uniaccount);
            
            if (is_error($result)) {
                return $result;
            }
    
            if (empty($result)) {
                return error(-1, '生成二维码失败');
            }
            
            $ticket     = $result['ticket'];
            $qrimg      = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . $ticket;
            $ims_qrcode = array(
                'uniacid' => $_W['uniacid'],
                'acid'    => $_W['acid'],
                'qrcid'   => floatval($result['scene_str']),
                "model"   => 2,
                "name"    => strtoupper(MODULE_PREFIX)."QRCODE",
                "keyword" => strtoupper(MODULE_NAME),
                "expire"  => 0,
                "createtime" => time(),
                "status"  => 1,
                'scene_str'=>$result['scene_str'],
                'url'     => $result['url'],
                "ticket"  => $result['ticket']
            );
    
            pdo_insert('qrcode', $ims_qrcode);
        }

        $qr = array(
            'uniacid' => $_W['uniacid'],
            'sceneid' => floatval($result['scene_str']),
            'scenestr'=> !empty($result['scene_str']) ? $result['scene_str'] : '',
            'url'     => !empty($result['url']) ? $result['url'] : '',
            "ticket"  => !empty($result['ticket']) ? $result['ticket'] : '',
            'qrimg'   => $qrimg,
            'posterid'=> $poster['id'],
            'createtime' => time(),
            'openid'  => $openid,
            'uid'     => $uid
        );

        pdo_insert(MODULE_PREFIX."qr", $qr);
        $qrid        = pdo_insertid();
        
        $key_word_pre = !empty($poster['reckeyword_prefix']) ? $poster['reckeyword_prefix'] : '';

        pdo_update(MODULE_PREFIX.'qr',array('reccode' => $key_word_pre . $qrid),array('id' => $qrid));

        $qr['id']    = $qrid;
        $qr['qrimg'] = $qrimg;
    }

    return $qr;
}

// 获取配置信息
function getConfig(){
	global $_W;
	$config = pdo_getcolumn('uni_account_modules', array('uniacid' => $_W['uniacid'], 'module' => MODULE_NAME), 'settings');
	$config = iunserializer($config);
	return $config;
}

function getFixedTicket($poster, $openid, $uniaccount){
    global $_W, $_GPC;
    $scene_str = md5(MODULE_NAME.":{$_W['uniacid']}:$openid:{$poster['id']}");

    $config = getConfig();

    if( $config['qrcode_type'] ){ // 临时
        $data = '{"expire_seconds": 2592000,"action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": "'.$scene_str.'"}}}';
    }else{// 永久
        $data = '{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "'.$scene_str.'"}}}';
    }

    $access_token = $uniaccount->fetch_token();
    $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $access_token;
    $res = chttp_post($url,$data);
    $content = @json_decode($res['content'], true);
    
    if (!is_array($content)) {
        return false;
    }
    if (!empty($content['errcode'])) {
        return error(-1, $content['errmsg']);
    }
	
    return array('barcode' => json_decode($data, true), 'ticket' => $content['ticket'],'url'=>$content['url'],'scene_str'=>$scene_str);
}

// 生成海报
function createPoster($poster, $member, $qr, $upload, $isxcx){
    global $_W;
    $path = IA_ROOT . "/addons/".MODULE_NAME."/static/data/" . $_W['uniacid'] . "/".intval($poster['id'])."/";
    
    load()->func('file');
    
    if (!is_dir($path)) {
        mkdirs($path);
    }

    $md5  = md5(json_encode(array('uid' => $member['uid'],'posterid' => $poster['id'])));

    $file = $md5.'.png';
    $img_path = IA_ROOT."/addons/".MODULE_NAME."/static/data/" . $_W['uniacid'] . "/" . intval($poster['id']) . "/" . $file;
    $img = $_W['siteroot'] . "addons/".MODULE_NAME."/static/data/" . $_W['uniacid'] . "/" . intval($poster['id']) .  "/" . $file;

    //缓冲一下
    if($upload){
		if($isxcx){
		}else{
			$waittext = !empty($poster["waittext"]) ? $poster["waittext"] : "邀请海报生成中，请等待片刻...";
            sendCustomNotice($member['openid'], $waittext);
		}
    }

    if($qr['createtime'] < time()-259200 || !$qr['mediaid'] || !is_file($img_path)){
        
        if(is_file($path.$qr['file'])){
            unlink($path.$qr['file']);
        }
        
        $cur_date = date("Ymd",time());
        
        # 缓冲....
        sendCustomNotice($member['openid'], "");
        
        
        //击败率
        $ratio = 0;
        
        set_time_limit(50);
        @ini_set('memory_limit', '256M');
        
        $bg     = createImage(tomedia($poster['bg']));
        $img_info = getimagesize(tomedia($poster['bg']));
        $width = $img_info[0];
        $height = $img_info[1];

        $target = imagecreatetruecolor($width, $height);
        imagecopy($target, $bg, 0, 0, 0, 0, $width, $height);
        imagedestroy($bg);

		load()->model('mc');
		$_W["account"] = uni_fetch($_W['uniacid']);
		$account_api = WeAccount::create();
		$token = $account_api->getAccessToken();
		$url = 'https://api.weixin.qq.com/cgi-bin/user/info?openid='.$member['openid'].'&lang=zh_CN&access_token='.$token;
		$res = ihttp_request($url);
	    $res = json_decode($res["content"],true);
		$member['nickname'] = $res['nickname'];
		$member['avatar'] = $res['headimgurl'];
		
        
        # 获取样本图片

        $data = json_decode(str_replace('&quot;', "'", $poster['data']), true);
        foreach ($data as $d) {
            $d = getRealData($d);
            if ($d['type'] == 'head') {
                $avatar = preg_replace('/\/0$/i', '/96', $member['avatar']);
                $target = mergeImage($target, $d, $avatar);
            }else if ($d['type'] == 'img') {
                $target = mergeImage($target, $d, $d['src']);
            }else if ($d['type'] == 'qr') {
                $target = mergeImage($target, $d, $qr['qrimg']);
            }else if ($d['type'] == 'nickname') {
                $target = mergeText($target, $d, $member['nickname']);
            }else if ($d['type'] == 'mobile') {
                $target = mergeText($target, $d, $member['mobile']);
            }else if ($d['type'] == 'date') {
                $target = mergeText($target, $d, date('Y.m.d',time()));
            }else if ($d['type'] == 'days') {
                if(intval($qr['updatenum']) < 10){
                    $qr['updatenum'] = "0".$qr['updatenum'];        
                }
                $target = mergeText($target, $d, $qr['updatenum']);
            }else if ($d['type'] == 'clock') {
                $target = mergeText($target, $d, $qr['clock_num']);
            }
            else if ($d['type'] == 'relay') {
                $poster_member_ranking = pdo_fetchcolumn("select ranking from ".tablename(MODULE_PREFIX."member")." where uniacid=:uniacid and uid=:uid order by id asc limit 1 ",array(':uniacid'=>$_W['uniacid'],':uid'=>$member['uid']));
                $relay = intval($poster_member_ranking) + intval($poster['relaystart']);
                $target = mergeText($target, $d, $relay);
            }else if ($d['type'] == 'relayday') {
                $mem_count_day = pdo_fetchcolumn("select count(*) from ".tablename(MODULE_PREFIX.'qr')." where uniacid = ".intval($_W['uniacid'])." and posterid = ".intval($poster['id'])." and updateday = ".intval($cur_date));
                $relayday = intval($mem_count_day) + intval($poster['relaystart']);
                $target = mergeText($target, $d, $relayday);
            }else if ($d['type'] == 'time') {
                $target = mergeText($target, $d, $qr['updatetime']);
            }else if ($d['type'] == 'realname') {
                $target = mergeText($target, $d, $member['realname']);
            }else if ($d['type'] == 'company') {
                $target = mergeText($target, $d, $member['company']);
            }
        }
        imagejpeg($target, $path . $file);
        imagedestroy($target);
        
        if(!empty($qr)){
            pdo_update(MODULE_PREFIX."qr", array(
                'file' => $file,
            ), array(
                'id' => $qr['id']
            ));
        }

        if ($upload) {
            $mediaid       = uploadImage($path . $file);
            
            $qr['mediaid'] = $mediaid;
            pdo_update(MODULE_PREFIX."qr", array(
                'mediaid' => $mediaid,
                'createtime' => time()
            ), array(
                'id' => $qr['id']
            ));
        }
    }
    
    return array(
        'img' => $img,
        'mediaid' => $qr['mediaid']
    );
}

/**
 * 图片定位
 * @param unknown $data
 * @return unknown
 */
function getRealData($data){
    $data['left']   = intval(str_replace('px', '', $data['left'])) * 2;
    $data['top']    = intval(str_replace('px', '', $data['top'])) * 2;
    $data['width']  = intval(str_replace('px', '', $data['width'])) * 2;
    $data['height'] = intval(str_replace('px', '', $data['height'])) * 2;
    $data['size']   = intval(str_replace('px', '', $data['size'])) * 2;
    $data['src']    = tomedia($data['src']);
    return $data;
}

/**
 * 绘制图片
 */
function mergeImage($target, $data, $imgurl){
    $img = createImage($imgurl);
    $w   = imagesx($img);
    $h   = imagesy($img);
    imagecopyresized($target, $img, $data['left'], $data['top'], 0, 0, $data['width'], $data['height'], $w, $h);
    imagedestroy($img);
    return $target;
}

/**
 * 绘制文本
 * @param unknown $target
 * @param unknown $data
 * @param unknown $text
 * @return unknown
 */
function mergeText($target, $data, $text){
    $font   = IA_ROOT . "/addons/".MODULE_NAME."/static/fonts/msyh.ttf";
    
    $colors = hex2rgb($data['color']);
    $color  = imagecolorallocate($target, $colors['red'], $colors['green'], $colors['blue']);
    
    $text = emoji($text);
    $text = mb_convert_encoding(strval($text), "html-entities", "utf-8");
    
    // imagettftext ( $target, $data['size'], 0, $data['left'] - (text_width($data['size'],$font,$text)/2), $data['top'] + $data['size'], $color, $font, $text );

    imagettftext($target, $data['size'], 0, $data['left'], $data['top'] + $data['size'], $color, $font, $text);
    return $target;
}

function get_bbox($size,$font,$text){
  return imagettfbbox($size, 0, $font, $text);
}

function text_height ($text) {
  $box = get_bbox($text);
  $height = $box[3] - $box[5];
  return $height;
}

function text_width ($text) {
  $box = get_bbox($text);
  $width = $box[4] - $box[6];
  return $width;
}

/**
 * 过滤emoji表情符号
 * @param unknown $text
 * @return mixed
 */
function emoji($text) {
    $clean_text = "";

    // Match Emoticons
    $regexEmoticons = '/[\x{1F600}-\x{1F64F}]/u';
    $clean_text = preg_replace($regexEmoticons, '', $text);

    // Match Miscellaneous Symbols and Pictographs
    $regexSymbols = '/[\x{1F300}-\x{1F5FF}]/u';
    $clean_text = preg_replace($regexSymbols, '', $clean_text);

    // Match Transport And Map Symbols
    $regexTransport = '/[\x{1F680}-\x{1F6FF}]/u';
    $clean_text = preg_replace($regexTransport, '', $clean_text);

    // Match Miscellaneous Symbols
    $regexMisc = '/[\x{2600}-\x{26FF}]/u';
    $clean_text = preg_replace($regexMisc, '', $clean_text);

    // Match Dingbats
    $regexDingbats = '/[\x{2700}-\x{27BF}]/u';
    $clean_text = preg_replace($regexDingbats, '', $clean_text);

    $regexDingbats = '/[\x{231a}-\x{23ab}\x{23e9}-\x{23ec}\x{23f0}-\x{23f3}]/u';
    $clean_text = preg_replace($regexDingbats, '', $clean_text);

    return $clean_text;
}

/**
 * 文字颜色
 * @param unknown $colour
 * @return boolean|multitype:number
 */
function hex2rgb($colour){
    if ($colour[0] == '#') {
        $colour = substr($colour, 1);
    }
    if (strlen($colour) == 6) {
        list($r, $g, $b) = array(
            $colour[0] . $colour[1],
            $colour[2] . $colour[3],
            $colour[4] . $colour[5]
        );
    } elseif (strlen($colour) == 3) {
        list($r, $g, $b) = array(
            $colour[0] . $colour[0],
            $colour[1] . $colour[1],
            $colour[2] . $colour[2]
        );
    } else {
        return false;
    }
    $r = hexdec($r);
    $g = hexdec($g);
    $b = hexdec($b);
    return array(
        'red' => $r,
        'green' => $g,
        'blue' => $b
    );
}

/**
 * 创建图片
 * @param unknown $imgurl
 * @return resource
 */
function createImage($imgurl){
    load()->func('communication');
    $resp = ihttp_request($imgurl);
    return imagecreatefromstring($resp['content']);
}

/**
 * 上传图片
 * @param unknown $img
 * @return Ambigous <string>
 */
function uploadImage($img){
    load()->func('communication');
    $account = getAccount();
    $access_token = $account->fetch_token();
    $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$access_token}&type=image";
    $curl = curl_init();
    $data = array('media' => '@' . $img);
    if (version_compare(PHP_VERSION, '5.5.0', '>')) {
        $data = array('media' => curl_file_create($img));
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    $content = @json_decode(curl_exec($curl), true);
    if (!is_array($content)) {
        $content = array('media_id' => '');
    }
    curl_close($curl);
    return $content['media_id'];
}

function postdata($value1,$value2,$value3,$value4,$value5){
    global $_W;
    if(empty($value1)){
        $value1 = "关注奖励到账通知";
    }
    if(empty($value2)){
        $value2 = "关注奖励";
    }
    if(empty($value3)){
        $value3 = "特此奖励";
    }
    if(empty($value4)){
        $value4 = "\r\n谢谢您对我们的支持！";
    }
    if(empty($value5)){
        $member = getMember($_W['openid']);
        if(!empty($member)){
            $value5 = "剩余积分【".$member['credit1']."分】,剩余余额【".$member['credit2']."元】";
        }else{
            $value5 = "";
        }
    }
    $postdata = array(
        'first' => array(
            'value' => $value1,
            "color" => "#4a5077"
        ),
        'keyword1' => array(
            'value' => $value2,
            "color" => "#4a5077"
        ),
        'keyword2' => array(
            'value' => $value3,
            "color" => "#4a5077"
        ),
        'keyword3' => array(
            'value' => $value5,
            "color" => "#4a5077"
        ),
        'remark' => array(
            'value' => $value4,
            "color" => "#4a5077"
        )
    );
    return $postdata;
}


// 累计AB营销数据
function up_level($uid,$parent_uid){
    global $_W;
    $uniacid = $_W['uniacid'];

    $member = pdo_fetch("select id,openid,uid,nickname,level,level_num,parentid from ".tablename(MODULE_PREFIX."member")." where uniacid = ".intval($_W['uniacid'])." and uid = ".intval($uid));

    if(empty($member['level_num']) && empty($member['parentid'])){
        $parent_member = pdo_fetch("select id,level_num,misterid from ".tablename(MODULE_PREFIX."member")." where uniacid =:uniacid and uid =:from_uid order by id desc limit 1",array(':uniacid'=>$uniacid,':from_uid'=>$parent_uid));

        if(!empty($parent_member)){
            if(empty($parent_member['level_num'])){
                $parent_member['misterid'] = $parent_member['id'];
            }
            pdo_update(MODULE_PREFIX."member",array('misterid' => $parent_member['misterid'],'level_num' => intval($parent_member['level_num']) + 1,'parentid'=>$parent_member['id']),array('id'=>$member['id']));
        }
    }

}

/**
 * 查询并更新用户三级营销
 */
function updateMemberLevel($uid,$poster){
    global $_W;
    $uniacid = $_W['uniacid'];

    $member = pdo_fetch("select id,openid,uid,nickname,level,level_num,parentid from ".tablename(MODULE_PREFIX."member")." where uniacid = ".intval($_W['uniacid'])." and uid = ".intval($uid));
    $nickname = $member['nickname'];
    
    if(!empty($member) && !empty($poster) ){

        // 营销模式 1,2,3
        if(empty($poster['level_type'])){
           return; 
        }

        $logs = pdo_fetch("select * from ".tablename(MODULE_PREFIX."log")." where uniacid = ".intval($_W['uniacid'])." and uid = ".intval($uid));

        // 上一级
        $level1_uid = $logs['from_uid']; 
        // 上上一级
        $level2_uid = empty($level1_uid) ? 0 : pdo_fetchcolumn("select from_uid from ".tablename(MODULE_PREFIX."log")." where uniacid = ".intval($_W['uniacid'])." and uid = ".$level1_uid);
        // 上上上一级
        $level3_uid = empty($level2_uid) ? 0 : pdo_fetchcolumn("select from_uid from ".tablename(MODULE_PREFIX."log")." where uniacid = ".intval($_W['uniacid'])." and uid = ".$level2_uid);
        
        // 开启一级营销
        if(intval($poster['level_type']) == 1){
            $level2_uid = 0;
            $level3_uid = 0;
        }
        elseif(intval($poster['level_type']) == 2){ 
            // 开启二级营销
            $level3_uid = 0;
        }

        // 获取当前等级
        if(!empty($level3_uid)){
            $level = 3;
        }elseif(!empty($level2_uid)){
            $level = 2;
        }elseif(!empty($level1_uid)){
            $level = 1;
        }

        $update_data = array('level'=>$level,'level1_uid'=>$level1_uid,'level2_uid'=>$level2_uid,'level3_uid'=>$level3_uid);

        pdo_update(MODULE_PREFIX."member",$update_data,array('uniacid'=>intval($_W['uniacid']),'uid' => $uid));

        // 累加级别
        up_level($uid,$logs['from_uid']);

        if(intval($poster['isopen_level']) == 1){

            $level0_val = $poster['level0_val'];
            $level0_url = $poster['level0_url'];
            
            if(!empty($level1_uid)){
                setCredit($level1_uid,'credit1', intval($poster['level1_credit']) , array($level1_uid,"我的一级会员-邀请好友关注获取积分！"));
                setCredit($level1_uid,'credit2', floatval($poster['level1_money']), array($level1_uid,"我的一级会员-邀请好友关注获取余额！"));
                $level1_val = $level0_val;
                $level1_val = str_replace("[nickname]", !empty($nickname) ? $nickname : "一级会员", $level1_val);
                $level1_val = str_replace("[credit1]", !empty($poster['level1_credit']) ? $poster['level1_credit'] : "0" ,$level1_val);
                $level1_val = str_replace("[credit2]", !empty($poster['level1_money']) ? $poster['level1_money'] : "0", $level1_val);
                $level1_val = str_replace("[level]", "一级", $level1_val);

                if(!empty($level0_url)){
                    if(empty($poster['templateid'])){
                        $level1_val = "<a href='".$level0_url."'>".$level1_val."</a>";
                    }
                }
                
                if(!empty($level1_val)){
                    $member1 = pdo_fetch("select openid,nickname from ".tablename(MODULE_PREFIX."member")." where uniacid = ".intval($_W['uniacid'])." and uid = ".intval($level1_uid));
                    if(!empty($poster['templateid'])){
                        sendTplNotice($member1['openid'], $poster['templateid'], postdata('','',$level1_val),$level0_url);
                    }else{
                        sendCustomNotice($member1['openid'], $level1_val);
                    }
                }
            }
            
            if(!empty($level2_uid)){

                setCredit($level2_uid,'credit1', intval($poster['level2_credit']) , array($level2_uid,"我的二级会员-邀请好友关注获取积分！"));
                setCredit($level2_uid,'credit2', floatval($poster['level2_money']), array($level2_uid,"我的二级会员-邀请好友关注获取余额！"));
                
                $level2_val = $level0_val;
                $level2_val = str_replace("[nickname]", !empty($nickname) ? $nickname : "二级会员", $level2_val);
                $level2_val = str_replace("[credit1]", !empty($poster['level2_credit']) ? $poster['level2_credit'] : "0" ,$level2_val);
                $level2_val = str_replace("[credit2]", !empty($poster['level2_money']) ? $poster['level2_money'] : "0", $level2_val);
                $level2_val = str_replace("[level]", "二级", $level2_val);
                
                if(!empty($level0_url)){
                    if(empty($poster['templateid'])){
                        $level2_val = "<a href='".$level0_url."'>".$level2_val."</a>";
                    }
                }

                if(!empty($level2_val)){
                    $member2 = pdo_fetch("select openid,nickname from ".tablename(MODULE_PREFIX."member")." where uniacid = ".intval($_W['uniacid'])." and uid = ".intval($level2_uid));
                    if(!empty($poster['templateid'])){
                        sendTplNotice($member2['openid'], $poster['templateid'], postdata('','',$level2_val),$level0_url);
                    }else{
                        sendCustomNotice($member2['openid'], $level2_val);
                    }
                }
            }
            
            if(!empty($level3_uid)){

                setCredit($level3_uid,'credit1', intval($poster['level2_credit']) , array($level3_uid,"我的三级会员-邀请好友关注获取积分！"));
                setCredit($level3_uid,'credit2', floatval($poster['level2_money']), array($level3_uid,"我的三级会员-邀请好友关注获取余额！"));
                
                $level3_val = $level0_val;
                $level3_val = str_replace("[nickname]", !empty($nickname) ? $nickname : "三级会员", $level3_val);
                $level3_val = str_replace("[credit1]", !empty($poster['level3_credit']) ? $poster['level3_credit'] : "0" ,$level3_val);
                $level3_val = str_replace("[credit2]", !empty($poster['level3_money']) ? $poster['level3_money'] : "0", $level3_val);
                $level3_val = str_replace("[level]", "三级", $level3_val);

                if(!empty($level0_url)){
                    if(empty($poster['templateid'])){
                        $level3_val = "<a href='".$level0_url."'>".$level3_val."</a>";
                    }
                }

                if(!empty($level2_val)){
                    $member3 = pdo_fetch("select openid,nickname from ".tablename(MODULE_PREFIX."member")." where uniacid = ".intval($_W['uniacid'])." and uid = ".intval($level3_uid));
                    if(!empty($poster['templateid'])){
                        sendTplNotice($member3['openid'], $poster['templateid'], postdata('','',$level3_val),$level0_url);
                    }else{
                        sendCustomNotice($member3['openid'], $level3_val);
                    }
                }

            }
            
        }

    }
}

